package com.anpy.management.service.impl;

import cn.hutool.core.util.StrUtil;
import com.anpy.management.entity.ProjectEntity;
import com.anpy.management.mapper.ProjectMapper;
import com.anpy.management.service.ProjectService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 项目服务实现类
 */
@Service
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, ProjectEntity> implements ProjectService {

    @Override
    public boolean createProject(ProjectEntity projectEntity) {
        // 设置创建时间和更新时间
        Date now = new Date();
        projectEntity.setCreatedAt(now);
        projectEntity.setUpdatedAt(now);
        return save(projectEntity);
    }

    @Override
    public boolean updateProject(ProjectEntity projectEntity) {
        // 设置更新时间
        projectEntity.setUpdatedAt(new Date());
        return updateById(projectEntity);
    }

    @Override
    public boolean deleteProject(Integer projectId) {
        return removeById(projectId);
    }

    @Override
    public ProjectEntity getProject(Integer projectId) {
        return getById(projectId);
    }

    @Override
    public List<ProjectEntity> getUserProjects(Long userId) {
        LambdaQueryWrapper<ProjectEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProjectEntity::getUserId, userId);
        queryWrapper.orderByDesc(ProjectEntity::getCreatedAt);
        return list(queryWrapper);
    }

    @Override
    public Page<ProjectEntity> getUserProjectsByPage(int page, int size, Integer userId, 
                                                    String projectType, String languageType, 
                                                    String projectStatus, String projectName) {
        LambdaQueryWrapper<ProjectEntity> queryWrapper = new LambdaQueryWrapper<>();
        
        // 必须条件：用户ID
        queryWrapper.eq(ProjectEntity::getUserId, userId);
        
        // 可选条件：项目类型
        if (StrUtil.isNotEmpty(projectType)) {
            queryWrapper.eq(ProjectEntity::getProjectType, projectType);
        }
        
        // 可选条件：语言类型
        if (StrUtil.isNotEmpty(languageType)) {
            queryWrapper.eq(ProjectEntity::getTechCategory, languageType);
        }
        
        // 可选条件：项目状态
        if (StrUtil.isNotEmpty(projectStatus)) {
            queryWrapper.eq(ProjectEntity::getProjectStatus, projectStatus);
        }
        
        // 可选条件：项目名称（模糊查询）
        if (StrUtil.isNotEmpty(projectName)) {
            queryWrapper.like(ProjectEntity::getProjectName, projectName);
        }
        
        // 按创建时间降序排序
        queryWrapper.orderByDesc(ProjectEntity::getCreatedAt);
        
        // 执行分页查询
        return page(new Page<>(page, size), queryWrapper);
    }
}
